<template>
  <div class="registerDetail">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="goBack" />
    <div class="top_detail">
      <div class="top_detail_lt">
        <div class="top_name">{{ dataSource.customerName }}</div>
        <div class="top_status">{{ dataSource.leadsBillStatus }}</div>
        <div class="top_txt">线索状态</div>
      </div>
      <div class="top_detail_rt">
        <div class="top_txt">
          <!-- {{ dataSource.phone }} -->
          <i @click="handleTel(dataSource.phone)" class="iconfont icon-tel"></i>
        </div>
        <div class="top_txt">{{ dataSource.followPerson ? dataSource.followPerson : '-' }}</div>
        <div class="top_txt">线索跟进人</div>
      </div>
    </div>
    <div>
      <van-field readonly v-model="dataSource.showOrgName" name="展厅" label="展厅" input-align="right" />
      <van-field readonly v-model="dataSource.leadsSource" name="线索来源" label="线索来源" input-align="right" />

      <van-field readonly v-model="dataSource.carModelName" name="车型名称" label="车型名称" input-align="right" />
      <van-field readonly v-model="dataSource.carNo" name="车牌号码" label="车牌号码" input-align="right" />
      <van-field readonly v-model="dataSource.carIsInShop" name="车辆是否在店" label="车辆是否在店" input-align="right" />
      <van-field readonly v-model="dataSource.providePerson" name="线索提供人" label="线索提供人" input-align="right" />
      <van-field readonly v-model="dataSource.bizDate" name="线索提供时间" label="线索提供时间" input-align="right" />
      <van-field required v-model="dataSource.note" name="备注" label="备注" type="textarea" input-align="left" placeholder />
      <van-field readonly v-model="dataSource.estimateBillStatus" name="评估工单状态" label="评估工单状态" input-align="right" />
      <van-field readonly v-model="dataSource.estimateTechName" name="评估师名称" label="评估师名称" input-align="right" />
      <van-field readonly v-model="dataSource.estimateTime" name="评估时间" label="评估时间" input-align="right" />
      <van-field readonly v-model="dataSource.estimatePrice" name="评估价格" label="评估价格" input-align="right" />
      <van-field readonly v-model="dataSource.contractNumber" name="采购合同编号" label="采购合同编号" input-align="right" @click="goContractDetail" />
    </div>
    <div class="followInfo">
      <div class="foll_title">跟进记录</div>

      <div class="followInfo_item flex" v-for="(item, index) in dataSource.followEntry" :key="index">
        <div class="followInfo_lt">
          <!-- <div class="followInfo_time">{{ item.followDate }}</div> -->
          <i class="iconfont icon-circle"></i>
        </div>

        <div class="followInfo_rt">
          <div class="followInfo_tt">
            <div class="followInfo_status">{{ item.followBillStatus }}</div>
            <div class="followInfo_time">{{ item.followDate }}</div>
          </div>
          <div class="followInfo_data">跟进人：{{ item.followPerson }}</div>
          <div class="followInfo_data">下次跟进时间：{{ item.nextFollowDate }}</div>
          <div class="followInfo_data">跟进日志：{{ item.followLog }}</div>
        </div>
      </div>
    </div>
    <!-- 转交 -->
    <van-dialog v-model="updateServiceVisible" title="请选择转交跟进人" show-cancel-button @confirm="updateServiceConfirm" :before-close="beforeCloseUpdateTel">
      <van-field v-model="updateServiceData.followPersonName" name="跟进人" label="跟进人" input-align="right" placeholder="请选择" readonly right-icon="arrow" @click="handleUpdateSelect()" />
    </van-dialog>
    <!-- 下拉选择弹窗 -->
    <van-popup v-model="showSelectPicker" position="bottom">
      <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="personName" />
    </van-popup>

    <!-- 操作面板 -->
    <van-share-sheet v-model="showShare" :options="options" @select="onSelect" />
    <div class="morebox">
      <div class="moreBtn" @click="handleShowDo">更多操作</div>
    </div>
    <!--
    <wx-open-launch-weapp
      id="launch-btn"
      appid="wx02e51afc29cecca4"
      path="/mall/vehicleAssess/edit/vehicleAssessEdit.html"
      class="wx-app"
    >
      评估申请
    </wx-open-launch-weapp>-->

    <!-- <wx-open-launch-weapp
      id="launch-btn"
      username="所需跳转的小程序原始id，即小程序对应的以gh_开头的id"
      path="/mall/vehicleAssess/purchase/vehicleAssessPurchase"
      @error="handleErrorFn"
      @launch="handleLaunchFn"
      class="wx-app"
    >采购申请</wx-open-launch-weapp>
    <div style="height:20px;width:20px">123</div>-->
  </div>
</template>

<script>
import {
  Empty,
  Field,
  Form,
  Tab,
  Tabs,
  ShareSheet,
  Dialog,
  Notify
} from "vant";
import { getCookies, isPhone } from "@/utils/util.js";
import icon_edit from "@/assets/images/icon_edit.png";
import icon_foll from "@/assets/images/icon_foll.png";
import icon_zj from "@/assets/images/icon_zj.png";
import ico_apply from "@/assets/images/ico_apply.png";
import icon_buy from "@/assets/images/icon_buy.png";
import icon_del from "@/assets/images/icon_del.png";
import sellManageApi from "@/api/sellManageApi";
import qs from "qs";
import { Base64 } from "@/utils/base";

import axios from "axios";
let baseObj = new Base64();

const base_url = process.env.BASE_API;
export default {
  name: "taskCenterDetail",
  components: {
    Empty,
    Field,
    Form,
    Tab,
    Tabs,
    ShareSheet,
    Dialog,
    Notify
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        billId: "", //单据ID
        customerName: "", //客户名称
        phone: "", //电话
        leadsBillStatus: "", //线索状态
        followPerson: "", //线索跟进人
        leadsSourse: "", //线索来源
        carNo: "", //车牌号
        carModelName: "", // 车型
        carIsInShop: "", // 是否到店处理
        providePerson: "", // 线索提供人
        bizDate: "", // 线索提供时间
        note: "", // 备注
        estimateBillStatus: "", //评估工作状态
        estimatePrice: "", //评估价格
        contractNumber: "", //采购合同编号
        contractNumberId: "",
        showOrgName: "",
        estimateId: ""
      },
      uploader: [],
      columns: [],
      showSelectPicker: false,
      disabled: false,
      detailId: "",
      tabActive: 0,
      userId: getCookies("userId"), //用户ID，必填，String
      showShare: false,
      options: [
        [
          { name: "编辑", icon: icon_edit, value: 1 },
          { name: "跟进", icon: icon_foll, value: 2 },
          { name: "转交", icon: icon_zj, value: 3 }
        ],
        [
          { name: "申请评估", icon: ico_apply, value: 4 },
          { name: "采购申请", icon: icon_buy, value: 5 },
          { name: "删除", icon: icon_del, value: 6 }
        ]
      ],
      updateServiceVisible: false,
      updateServiceData: {
        followPersonId: "",
        followPersonName: ""
      },
      followPersonList: [],
      userInfo: {}
    };
  },

  mounted() {
    // if (this.$route.query) {
    if (localStorage.getItem("billId") && !localStorage.getItem("skipUrl")) {
      this.detailId = localStorage.getItem("billId");
      this.getDetail(this.detailId);
      this.getPurchaseLeadsFollowPerson();
    }
    console.log(baseObj.decode("eG93ZFBVcnBUT212Ym1JMzU4MmZiTW1sTFdFPQ=="));
    if (localStorage.getItem("skipUrl")) {
      if (localStorage.getItem("isGet") != 2) {
        this.leadsPurchaseTrigger();
      }
      this.getDetail(baseObj.decode(localStorage.getItem("assBillId")));
      this.detailId = baseObj.decode(localStorage.getItem("assBillId"));
      localStorage.setItem("billId", this.detailId);
      localStorage.setItem("skipUrl", "");
      this.getPurchaseLeadsFollowPerson();

      console.log(456);
    }
    if (localStorage.getItem("userInfo")) {
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      console.log(this.userInfo);
    }
  },
  methods: {
    // 自动获取线索
    leadsPurchaseTrigger() {
      sellManageApi
        .secondHandCarFacade({
          method: "leadsPurchaseTrigger", //固定值
          billId: baseObj.decode(localStorage.getItem("assBillId"))
        })
        .then(res => {
          if (res.code == 1) {
            Notify({ type: "success", message: "线索领取成功" });
            this.getDetail(baseObj.decode(localStorage.getItem("assBillId")));
          }
        });
    },

    getDetail(billId) {
      sellManageApi
        .secondHandCarFacade({
          method: "getPurchaseLeadsById", //固定值
          billId //单据Id，必填，String
        })
        .then(res => {
          if (res.code == 1) {
            res.data.estimatePrice = res.data.estimatePrice
              ? res.data.estimatePrice + " （万元）"
              : res.data.estimatePrice;
            this.dataSource = res.data;
          }
        });
    },

    handleShowDo() {
      this.showShare = true;
    },
    onSelect(option) {
      // console.log(option)
      let vm = this;
      if (option.value == 1) {
        if (this.dataSource.leadsBillStatus != "保存") {
          Notify({ type: "danger", message: "当前单据状态不能编辑" });
          return;
        }
        this.$router.push({
          path: "assessManageEdit",
          query: { billId: this.dataSource.billId }
        });
      }
      if (option.value == 2) {
        if (this.dataSource.leadsBillStatus == "待认领") {
          Notify({ type: "danger", message: "当前单据状态不能添加跟进记录" });
          return;
        }
        this.$router.push({
          path: "assessManageFollow",
          query: {
            billId: vm.dataSource.billId ? vm.dataSource.billId : vm.detailId
          }
        });
      }
      if (option.value == 3) {
        this.updateServiceVisible = true;
      }
      if (option.value == 4) {
        if (this.dataSource.estimateId) {
          Notify({ type: "danger", message: "该线索已经生成评估工单" });
          return;
        }
        Dialog.confirm({
          title: "提示",
          message: `确定申请评估？`
        })
          .then(() => {
            vm.applyEst(option.value);
          })
          .catch(() => {
            console.log("取消");
            // on cancel
          });
      }
      if (option.value == 5) {
        if (vm.userInfo.kdusername != vm.dataSource.followPerson) {
          Notify({
            type: "danger",
            message: "你不是当前线索跟进人，无法进行采购申请"
          });
          return;
        }
        if (!vm.dataSource.estimateId) {
          Notify({
            type: "danger",
            message: "该线索未生成对应评估工单，无法进行采购申请"
          });
          return;
        }
        Dialog.confirm({
          title: "提示",
          message: `确定申请采购？`
        })
          .then(() => {
            vm.applyEst(option.value);
          })
          .catch(() => {
            console.log("取消");
            // on cancel
          });
      }
      if (option.value == 6) {
        if (this.dataSource.leadsBillStatus != "保存") {
          Notify({ type: "danger", message: "当前单据状态不能编辑" });
          return;
        }
        Dialog.confirm({
          title: "提示",
          message: "确认删除？"
        })
          .then(() => {
            this.removePurchaseLeads();
            // console.log("删除");
          })
          .catch(() => {
            console.log("取消");
            // on cancel
          });
      }
      this.showShare = false;
    },
    // 评估申请跳转小程序
    applyEst(type) {
      let vm = this;
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: "post",
        data: qs.stringify(
          // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
          { url: location.href.split("?")[0], type: "app" },
          { encode: false }
        ),
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          satoken: getCookies("token")
        }
      }).then(res => {
        console.log("jsdkConfig:", res);
        let jsdk = res.data.data;
        localStorage.setItem("jsdk", JSON.stringify(res.data.data));

        wx.agentConfig({
          corpid: jsdk.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
          agentid: jsdk.agentid, // 必填，企业微信的应用id （e.g. 1000247）
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
          jsApiList: ["launchMiniprogram"], //必填，传入需要使用的接口名称
          success: function(res) {
            console.log("agentConfig权限成功返回信息:", res);
            // wx9e482fe1abf18c87
            // appid: 'wx02e51afc29cecca4', // 需跳转的小程序appid
            if (type == 4) {
              console.log("线索id1：", vm.detailId);
              console.log("线索id2：", localStorage.getItem("billId"));
              // 申请评估
              console.log(
                "申请评估跳转地址：",
                `/mall/vehicleAssess/edit/vehicleAssessEdit?ysc=1&username=${
                  vm.userInfo ? vm.userInfo.kdaccount : "zhangdx"
                }&clueId=${encodeURIComponent(vm.detailId)}`
              );
              // return;
              wx.invoke(
                "launchMiniprogram",
                {
                  appid: "wx02e51afc29cecca4", // 需跳转的小程序appid
                  // appid: 'wx9e482fe1abf18c87', // 测试跳转的appid
                  path: `/mall/vehicleAssess/edit/vehicleAssessEdit?ysc=1&username=${
                    vm.userInfo ? vm.userInfo.kdaccount : "zhangdx"
                  }&clueId=${encodeURIComponent(vm.detailId)}` // 所需跳转的小程序内页面路径及参数。非必填
                },
                function(res) {
                  if (res.err_msg == "launchMiniprogram:ok") {
                    // 正常
                  } else {
                    // 错误处理
                  }
                }
              );
            }

            // 申请采购
            if (type == 5) {
              console.log(
                "申请采购跳转地址：",
                `/mall/vehicleAssess/purchase/vehicleAssessPurchase?ysc=1&username=${
                  vm.userInfo ? vm.userInfo.kdaccount : "zhangdx"
                }&id=${vm.dataSource.estimateId}`
              );
              wx.invoke(
                "launchMiniprogram",
                {
                  appid: "wx02e51afc29cecca4", // 需跳转的小程序appid
                  path: `/mall/vehicleAssess/purchase/vehicleAssessPurchase?ysc=1&username=${
                    vm.userInfo ? vm.userInfo.kdaccount : "zhangdx"
                  }&id=${vm.dataSource.estimateId}` // 所需跳转的小程序内页面路径及参数。非必填
                },
                function(res) {
                  if (res.err_msg == "launchMiniprogram:ok") {
                    // 正常
                  } else {
                    // 错误处理
                  }
                }
              );
            }
          },
          fail: function(res) {
            console.log("agentConfig权限失败返回信息:", res);
            if (res.errMsg.indexOf("function not exist") > -1) {
              alert("版本过低请升级");
            }
          }
        });
      });
    },

    // 跟进人
    getPurchaseLeadsFollowPerson() {
      sellManageApi
        .secondHandCarFacade({
          method: "getPurchaseLeadsFollowPerson", //固定值
          billId: this.detailId
        })
        .then(res => {
          if (res.code == 1) {
            this.followPersonList = res.data;
          }
        });
    },
    // 删除
    removePurchaseLeads() {
      sellManageApi
        .secondHandCarFacade({
          method: "removePurchaseLeads", //固定值
          billId: this.detailId
        })
        .then(res => {
          if (res.code == 1) {
            this.followPersonList = res.data;
            this.$router.push({ path: "/assessManage", query: { type: 1 } });
          }
        });
    },
    // 确认转交
    updateServiceConfirm() {
      if (!this.updateServiceData.followPersonId) {
        Notify({ type: "danger", message: "请选择跟进人" });
        return;
      }
      console.log(this.detailId);
      // return
      sellManageApi
        .secondHandCarFacade({
          billId: this.detailId,
          ...this.updateServiceData,
          method: "followPurchaseLeads"
        })
        .then(res => {
          if (res.code == 1) {
            Notify({ type: "success", message: "转交成功" });
            this.initData();
          } else {
            Notify({ type: "danger", message: res.errorMessage });
          }
        });

      this.updateServiceVisible = false;
    },
    beforeCloseUpdateTel(action, done) {
      if (action === "confirm") {
        return done(false);
      } else {
        return done();
      }
    },
    handleUpdateSelect() {
      this.showSelectPicker = true;
      this.columns = this.followPersonList;
      // this.columns = [
      //   {
      //     personId: '111', //转交人ID
      //     personName: '章三', //转交人名称
      //     personNumber: '', //转交人编码
      //   },
      // ]
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.updateServiceData.followPersonName = value.personName;
      this.updateServiceData.followPersonId = value.personId;

      this.showSelectPicker = false;
    },
    goBack() {
      this.$router.push("/assessManage");
    },
    goContractDetail() {
      if (this.dataSource.contractNumberId) {
        this.$router.push({
          path: "/buyContractDetail",
          query: { billId: this.dataSource.contractNumberId }
        });
      }
    },
    handleTel(tel) {
      if (isPhone()) {
        window.location.href = `tel:${tel}`;
      } else {
        Notify({ type: "danger", message: "请在手机端使用此功能" });
      }
    }
  }
};
</script>

<style lang="less" scoped>
body {
  background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  padding-bottom: 75px;
  .top_detail {
    display: flex;
    align-items: center;
    // width: 100%;
    background: #fff;
    padding: 10px;
    margin: 10px;
    .top_detail_lt {
      display: inline-block;
      text-align: center;
      width: 50%;
      border-right: 1px solid #f0f0f0;
    }
    .top_detail_rt {
      width: 50%;
      display: inline-block;
      text-align: center;
    }
    .top_name {
      font-weight: bold;
      font-size: 13px;
      margin-bottom: 5px;
    }
    .top_status {
      color: red;
      font-size: 12px;
      margin-bottom: 5px;
    }
    .top_txt {
      font-size: 12px;
      color: #333;
      margin-bottom: 5px;
      .icon-tel {
        background: #35bc04;
        color: #fff;
        border-radius: 50%;
        padding: 5px;
      }
    }
  }
}

// 跟进信息
.followInfo {
  padding: 10px;
  background: #fff;

  .foll_title {
    box-sizing: border-box;
    color: #646566;
    text-align: left;
    font-size: 15px;
    padding: 5px 10px 5px 5px;
    margin-bottom: 10px;
  }
  .followInfo_item {
    margin-bottom: 10px;
    position: relative;
    .followInfo_lt {
      width: 20%;
      .followInfo_time {
        font-size: 14px;
        color: #666;
        position: absolute;
        top: 5px;
      }
      &::before {
        content: "";
        height: 130px;
        width: 1px;
        background: #ccc;
        position: absolute;
        top: 0px;
        left: 20px;
      }
      .icon-circle {
        color: #ccc;
        z-index: 2;
        position: absolute;
        top: 0px;
        left: 0.22rem;
        background: #fff;
      }
    }
    .followInfo_rt {
      background: #f1f1f1;
      width: 80%;
      padding: 15px 0 15px 15px;
      border-radius: 4px;
      .followInfo_tt {
        display: flex;
        align-items: center;
        border: 1px solid #02c081;
        font-size: 12px;
        border-radius: 3px;
        margin-bottom: 5px;
        width: 200px;

        .followInfo_status {
          background: #02c081;
          color: #fff;
          padding: 5px;
        }
        .followInfo_time {
          padding: 5px;
          margin-left: 5px;
        }
      }
      .followInfo_num {
        font-size: 14px;
        color: #333;
        margin-bottom: 5px;
      }
      .followInfo_data {
        font-size: 13px;
        color: #666;
        margin-bottom: 5px;
        .followInfo_img {
          width: 40px;
          height: 40px;
          margin-right: 5px;
        }
      }
    }
  }
}
.morebox {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 99;
  width: 100%;
  background: #fff;
  .moreBtn {
    background: #409eff;
    color: #fff;
    width: 75%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    margin-top: 15px;
    font-size: 15px;
    margin-bottom: 25px;
  }
}
</style>
